<?php

declare (strict_types=1);

namespace app\admin\controller\file;


use app\common\model\file\FileModel;
use app\common\service\FileService;
use app\common\service\TencentOssUploader;
use app\common\service\UploadService;
use app\admin\controller\Controller;
use think\facade\Config;
use think\helper\Str;
use app\admin\controller\CosUpload;
class Upload extends Controller
{

    protected array $middleware = [
        'admin'     => ['except'     => ['images']],
    ];
    /**
     * 上传图片
     */
    public function images()
    {
//        $groupId = request()->post('group_id',0);
//        $res = UploadService::upload('image',$groupId);
//        $cosUpload = new CosUpload();
//        $res = $cosUpload ->simpleUpload();
        $groupId = request()->post('group_id',0);
        if (!$_FILES['file']) {
            return error('请选择要上传的文件');
        }
        $file = $_FILES['file'];
        $type = explode('/', $file['type']);
        if(!in_array($type[1], config('admin.file_image'))) {
            return error('不允许上传的文件类型');
        }
        try {
            // 2. 实例化上传类
            $ossUploader = new TencentOssUploader();
            $uploads = 'uploads/';
            $saveDir = $uploads  . date('Ymd');
            // 3. 上传表单文件
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {

                $result = $ossUploader->uploadHttpFile($file, $uploads);

                if ($result['success']) {
                    $ossFile = $result['data']['ossFile'];
                    $data = [
                        'admin_id' => 0,
                        'group_id' => $groupId,
                        'storage_path' => $saveDir,
                        'url' => Config::get('admin.cos_domain') . $result['data']['url'],
                        'hash' => Str::random(32),
                        'origin_name' => $file['name'],
                        'object_name' => $ossFile['fileName'],
                        'mimetype' => $file['type'],
                        'extension' => $type[1],
                        'media_type' => $type[0],
                        'filesize' => $file['size']
                    ];
                    // 4、写入数据库中
                    $file = FileModel::create($data);
//                    return  $data;
//                    return success('上传成功', [
//                        'url' => Config::get('admin.cos_domain') . $result['data']['url'],
//                        'path' =>  $result['data']['path']
//                    ]);
                } else {
                    return error($result['message']);

                }
            }


        } catch (Exception $e) {
            return error($e->getMessage());
        }
        return success($data);
    }
    /**
     * 上传图片
     */
    public function image()
    {
//        $groupId = request()->post('group_id',0);
//        $res = UploadService::upload('image',$groupId);
//        $cosUpload = new CosUpload();
//        $res = $cosUpload ->simpleUpload();
        $groupId = request()->post('group_id',0);
        if (!$_FILES['file']) {
            return error('请选择要上传的文件');
        }
        $file = $_FILES['file'];
        $type = explode('/', $file['type']);
        if(!in_array($type[1], config('admin.file_image'))) {
            return error('不允许上传的文件类型');
        }
        try {
            // 2. 实例化上传类
            $ossUploader = new TencentOssUploader();
            $uploads = 'uploads/';
            $saveDir = $uploads  . date('Ymd');
            // 3. 上传表单文件
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {

                $result = $ossUploader->uploadHttpFile($file, $uploads);

                if ($result['success']) {
                    $ossFile = $result['data']['ossFile'];
                    $data = [
                        'admin_id' => 0,
                        'group_id' => $groupId,
                        'storage_path' => $saveDir,
                        'url' => Config::get('admin.cos_domain') . $result['data']['url'],
                        'hash' => Str::random(32),
                        'origin_name' => $file['name'],
                        'object_name' => $ossFile['fileName'],
                        'mimetype' => $file['type'],
                        'extension' => $type[1],
                        'media_type' => $type[0],
                        'filesize' => $file['size']
                    ];
                    // 4、写入数据库中
                    $file = FileModel::create($data);
//                    return  $data;
//                    return success('上传成功', [
//                        'url' => Config::get('admin.cos_domain') . $result['data']['url'],
//                        'path' =>  $result['data']['path']
//                    ]);
                } else {
                    return error($result['message']);

                }
            }


        } catch (Exception $e) {
            return error($e->getMessage());
        }
        return success($data);
    }

    /**
     * 上传视频
     */
    public function video()
    {
//        $res = runtime_path('chunk/test.mp4');
//        $groupId = request()->post('group_id',0);
//        $res = UploadService::upload('video',$groupId);

//        $cosUpload = new CosUpload();
//        $res = $cosUpload ->sliceUpload();
        $groupId = request()->post('group_id',0);
        if (!$_FILES['file']) {
            return error('请选择要上传的文件');
        }
        $file = $_FILES['file'];
        $type = explode('/', $file['type']);
        if(!in_array($type[1], config('admin.file_video'))) {
            return error('不允许上传的文件类型');
        }
        try {
            // 2. 实例化上传类
            $ossUploader = new TencentOssUploader();

            // 3. 上传表单文件
            if ($_SERVER['REQUEST_METHOD'] === 'POST') {
                // 生成存储路径
                $uploads = 'uploads/';
                $saveDir = $uploads  . date('Ymd');

                $ossFilePath = $ossUploader->generateOssPath($file['name'],'uploads/');
                $result = $ossUploader->uploadLargeFile($file['tmp_name'], $ossFilePath['path']);

                trace('分片上传大文件'.date("Y-m-d H:i:s").json_encode($result,256));
                if ($result['success']) {

//                    $ossFile = $result['data']['ossFile'];

                    $data = [
                        'admin_id' => 0,
                        'group_id' => $groupId,
                        'storage_path' => $saveDir,
                        'url' => Config::get('admin.cos_domain') . $result['data']['url'],
                        'hash' => Str::random(32),
                        'origin_name' => $file['name'],
                        'object_name' => $ossFilePath['fileName'],
                        'mimetype' => $file['type'],
                        'extension' => $type[1],
                        'media_type' => $type[0],
                        'filesize' => $file['size']
                    ];
                    // 4、写入数据库中
                    $file = FileModel::create($data);




//                    return success('上传成功', [
//                        'url' => Config::get('admin.cos_domain') . $result['data']['url'],
//                        'path' =>  $result['data']['path']
//                    ]);
                } else {
                    return error($result['message']);

                }
            }

            // 4. 上传本地文件示例
            // $localFile = '/path/to/local/file.jpg';
            // $ossPath = 'files/image.jpg';
            // $result = $ossUploader->uploadFile($localFile, $ossPath);

            // 5. 上传大文件示例(分片上传)
            // $largeFile = '/path/to/large/file.zip';
            // $ossPath = 'files/large.zip';
            // $result = $ossUploader->uploadLargeFile($largeFile, $ossPath);

        } catch (Exception $e) {
            return error($e->getMessage());
        }

        return success($data);
    }

    /**
     * 上传文件
     */
    public function file()
    {
        $groupId = request()->post('group_id',0);
        $res = UploadService::upload('file',$groupId);
        return success($res);
    }


    /**
     * 上传证书
     */
    public function cert()
    {
        $groupId = request()->post('group_id',0);
        $res = UploadService::upload('cert',$groupId);
        $res['root_path'] = public_path().$res['storage_path'].DIRECTORY_SEPARATOR.$res['object_name']; 
        return success($res);
        
    }
}